﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;

namespace StarHelper
{
    /// <summary>
    /// 枚举帮助类
    /// </summary>
    public static class EnumHelper
    {
        /// <summary>
        /// 获取枚举的备注信息
        /// </summary>
        /// <param name="em"></param>
        /// <returns></returns>
        public static string GetRemark(this Enum value)
        {
            try
            {

                FieldInfo fi = value.GetType().GetField(value.ToString());
                if (fi == null)
                {
                    return value.ToString();
                }
                object[] attributes = fi.GetCustomAttributes(typeof(RemarkAttribute), false);
                if (attributes.Length > 0)
                {
                    return ((RemarkAttribute)attributes[0]).Remark;
                }
                else
                {
                    return value.ToString();
                }
            }
            catch
            {
                return value.ToString();
            }
        }

        public static string GetEnumDescription(this Enum value)
        {
            try
            {

                FieldInfo fi = value.GetType().GetField(value.ToString());
                DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
                if (attributes.Length > 0)
                {
                    return attributes[0].Description;
                }
                else
                {
                    return value.ToString();
                }
            }
            catch
            {
                return value.ToString();
            }

        }

        /// <summary>
        /// 枚举转成集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<EnumHelperDto> EnumToList<T>()
        {
            List<EnumHelperDto> list = new List<EnumHelperDto>();
            foreach (var e in Enum.GetValues(typeof(T)))
            {
                EnumHelperDto m = new EnumHelperDto();
                object[] objArr = e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), true);
                m.code = Convert.ToInt32(e);
                m.name = e.ToString();
                list.Add(m);
            }
            return list;
        }
    }
    /// <summary>
    /// 备注特性
    /// </summary>
    public class RemarkAttribute : Attribute
    {
        /// <summary>
        /// 备注
        /// </summary>
        public string Remark { get; set; }

        public RemarkAttribute(string remark)
        {
            this.Remark = remark;
        }
    }

    public class EnumHelperDto
    {
        public int code { get; set; }
        public string name { get; set; }
    }
}
